﻿#include "fancon__imei.h"
#include "ui_fancon__imei.h"
#include "txt.h"
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QFileInfo>

Fancon__IMEI::Fancon__IMEI(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Fancon__IMEI)
{
    ui->setupUi(this);

}

Fancon__IMEI::~Fancon__IMEI()
{
    delete ui;
}

void Fancon__IMEI::on_pushButton_clicked()  //单个IMEI的cd码计算
{
    QString imei ;
    char* IN ;
    imei = ui->lineEdit->text();

    QByteArray ba = imei.toLatin1();
    IN=ba.data();
    int len = ba.length();

    int cd = get_imei(IN , len) ;

    QString Scd = QString::number(cd);

    if(cd == -1 || len != 14)
    {
        ui->label_3->setText("err");
        ui->lineEdit_2->setText("err");
    }
    else
    {
        ui->label_3->setText(Scd);
        ui->lineEdit_2->setText(imei+Scd);
    }
}


int Fancon__IMEI::get_imei(char* imei ,int len)  //cd码计算逻辑
{
    int tmp[14];

    for(int i=0 ; i < len ;i++)
    {

        tmp[i]=imei[i] - 48;
        if(tmp[i]<0 || tmp[i] > 9 )
            return -1;
    }

    for(int i=0 ; i < len ;i++)
    {
        i++;
        tmp[i]*=2;
    }

    for(int i=0 ; i < len ;i++)
    {
        i++;
        if(tmp[i] >= 10)
        {
            tmp[i]-=9;
        }
    }

    int sum_imei = 0;
    for(int i=0 ; i < len ;i++)
    {
        sum_imei+=tmp[i];
    }

    if(sum_imei%10 == 0)
    {
        return 0;
    }
    else
    {
        imei_cd=10 - (sum_imei % 10) ;
        return imei_cd ;
    }
}

void Fancon__IMEI::on_pushButton_3_clicked()  //批量IMEI的cd码计算
{
    ui->textEdit_2->clear();
    QString ch = ui->textEdit->toPlainText();

    int len = ch.length();   
    if (len == 0)
    {
        QString HH = QString("请在左边方框%1输入14位IMEI数据!").arg('\n');
        ui->textEdit_2->setText(HH);
        return;
    }

    qDebug()<< len;

    int i = 0;
    char *IN;


     while(len >= 0)
    {
         QString strq(ch);

         strq = strq.mid(i*14+i,14);

         QByteArray ba = strq.toLatin1();
         IN=ba.data();

         int cd = get_imei(IN , 14);
         QString Scd = QString::number(cd);

         QString  tmp = QString(strq+Scd) ;

         if(cd == -1 )
         {
              ui->textEdit_2->append("输入有误！!");
              return;
         }
         else
         {
              ui->textEdit_2->append(tmp);
         }

         qDebug()<< tmp;
         i++;

         if(i == 0)
            len=len - 14 ;
         else
            len=len - 15 ;

    }

}

void Fancon__IMEI::on_pushButton_4_clicked()  //跳转文本IMEI转换
{
    Txt *txtwin = new Txt(this) ;
    txtwin->show();
    this->hide();
}

void Fancon__IMEI::on_pushButton_2_clicked()   //清除批量生成内容
{
    ui->textEdit->clear();
    ui->textEdit_2->clear();
}
